package com.apes.framework.plugin.esb.processor.jpa;

import com.apes.framework.plugin.esb.api.Request;
import com.apes.framework.plugin.esb.processor.AbstractChainProcessor;
import com.apes.framework.util.MapUtil;
import lombok.Data;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 功能：
 *
 * @author xul
 * @create 2018-12-03 14:17
 */
@Data
public class FilterProcessor<T extends Request, R> extends AbstractChainProcessor<T, R> {
    private List<Map<String, Object>> filters;

    @Override
    protected R doProcess(T source) {
        Map result = source.getMap();
        List conditions = createFilters(result);
        if (result.containsKey("condition")) {
            List<Map<String, Object>> filters = (List<Map<String, Object>>) result.get("condition");
            if (this.filters != null) filters.addAll(conditions);
        } else if (result.containsKey("group")) {
            Map group = (Map) result.get("group");
            if (this.filters != null) {
                result.put("group", MapUtil.mapper("filters", conditions, "groups", new Map[]{group}, "operator", "and"));
            }
        }
        return (R) result;
    }

    private List<Map<String, Object>> createFilters(Map result) {
        List<Map<String, Object>> returnList = new ArrayList<>();
        for (int i = 0, len = filters.size(); i < len; i++) {
            Map m = new HashMap<String, Object>();
            Map<String, Object> filter = filters.get(i);
            Iterator<String> iterator = filter.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                m.put(key, replace(filter.get(key), result));
            }
            returnList.add(m);
        }
        return returnList;
    }


    public Object replace(Object value, Map source) {
        if (value == null) return value;
        String s = !(value instanceof String) ? String.valueOf(value) : (String) value;
        String variable = getVariable(s);

        if (variable == null) {
            return value;
        } else if (variable.equalsIgnoreCase("current_date")) {
            return Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant());
        } else {
            if (source.get(value) != null) {
                return source.get(value);
            } else {
                throw new RuntimeException("未找到对应的处理逻辑，请补全！ 当前处理字段：" + value);
            }
        }
    }


    private String getVariable(String value) {
        String regex = "(\\{\\{)(.+?)(}})";
        return getVariable(regex, value);
    }

    private String getVariable(String regex, String value) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(value);
        if (matcher.find()) {
            return matcher.group(2).trim();
        }
        return null;
    }

}
